package cn.wolfcode.wms.service.impl;


import cn.wolfcode.wms.domain.Employee;
import cn.wolfcode.wms.domain.StockIncomeBill;
import cn.wolfcode.wms.domain.StockIncomeBillItem;
import cn.wolfcode.wms.exception.LogicException;
import cn.wolfcode.wms.mapper.StockIncomeBillItemMapper;
import cn.wolfcode.wms.mapper.StockIncomeBillMapper;
import cn.wolfcode.wms.page.PageResult;
import cn.wolfcode.wms.qo.QueryObject;
import cn.wolfcode.wms.service.IProductStockService;
import cn.wolfcode.wms.service.IStockIncomeBillService;
import cn.wolfcode.wms.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

@Service
public class StockIncomeBillServiceImpl implements IStockIncomeBillService {

    @Autowired
    private StockIncomeBillMapper stockIncomeBillMapper;
    @Autowired
    private StockIncomeBillItemMapper stockIncomeBillItemMapper;
    @Autowired
    private IProductStockService productStockService;

    public StockIncomeBill getById(Long id) {
        return stockIncomeBillMapper.selectByPrimaryKey(id);
    }

    public void saveOrUpdate(StockIncomeBill stockIncomeBill) {
        if (stockIncomeBill.getId() != null) {
            update(stockIncomeBill);
        } else {
            save(stockIncomeBill);
        }
    }

    /**
     * 具体的新增逻辑
     *
     * @param stockIncomeBill
     */
    private void save(StockIncomeBill stockIncomeBill) {
        //1.获取当前用户,设置录入人相关信息
        Employee currentUser = UserContext.getcurrentUser();
        stockIncomeBill.setInputTime(new Date());
        stockIncomeBill.setInputUser(currentUser);
        //2.重置订单状态为为未审核
        stockIncomeBill.setStatus(StockIncomeBill.STATUS_NORMAL);
        //3.计算总金额和数量
        BigDecimal totalAmount = BigDecimal.ZERO;
        BigDecimal totalNumber = BigDecimal.ZERO;
        //4.遍历订单明细
        for (StockIncomeBillItem item : stockIncomeBill.getItems()) {
            //5.计算明细金额小计,并设置到明细中
            BigDecimal amount = item.getNumber().multiply(item.getCostPrice()).setScale(2, RoundingMode.HALF_UP);
            item.setAmount(amount);
            //6.累加总金额和总数量
            totalAmount = totalAmount.add(amount);
            totalNumber = totalNumber.add(item.getNumber());

        }
        //7.设置订单总金额和总数量
        stockIncomeBill.setTotalAmount(totalAmount);
        stockIncomeBill.setTotalNumber(totalNumber);
        //8.保存订单
        stockIncomeBillMapper.insert(stockIncomeBill);
        //9.为所有明细设置订单id,并保存明细
        for (StockIncomeBillItem item : stockIncomeBill.getItems()) {
            item.setBillId(stockIncomeBill.getId());
            stockIncomeBillItemMapper.insert(item);
        }

    }

    private void update(StockIncomeBill stockIncomeBill) {
        StockIncomeBill sib = stockIncomeBillMapper.selectByPrimaryKey(stockIncomeBill.getId());
        if (sib.getStatus() == StockIncomeBill.STATUS_AUDITED) {
            throw new LogicException("已经审核,无法更新");
        }
        //1.删除原来的订单明细
        stockIncomeBillItemMapper.deleteByBillId(stockIncomeBill.getId());
        //2.计算总金额和总数量
        BigDecimal totalAmount = BigDecimal.ZERO;
        BigDecimal totalNumber = BigDecimal.ZERO;
        //3.遍历明细,计算明细金额小计,
        for (StockIncomeBillItem item : stockIncomeBill.getItems()) {
            BigDecimal amount = item.getNumber().multiply(item.getCostPrice()).setScale(2, RoundingMode.HALF_UP);
            item.setAmount(amount);
            //为明细设置订单,并保存明细
            item.setBillId(stockIncomeBill.getId());
            stockIncomeBillItemMapper.insert(item);
            //累加总金额和总数量
            totalAmount = totalAmount.add(amount);
            totalNumber = totalNumber.add(item.getNumber());
        }
        //设置订单总金额和总数量
        stockIncomeBill.setTotalAmount(totalAmount);
        stockIncomeBill.setTotalNumber(totalNumber);
        //更新订单
        stockIncomeBillMapper.updateByPrimaryKey(stockIncomeBill);
    }

    public void delete(Long id) {
        StockIncomeBill sib = stockIncomeBillMapper.selectByPrimaryKey(id);
        if (sib.getStatus() == StockIncomeBill.STATUS_AUDITED) {
            throw new LogicException("已经审核,无法删除");
        }
        //删除明细
        stockIncomeBillItemMapper.deleteByBillId(id);

        stockIncomeBillMapper.deleteByPrimaryKey(id);
    }

    public PageResult query(QueryObject qo) {
        int rows = stockIncomeBillMapper.queryForCount(qo);
        if (rows == 0) {
            return PageResult.empty(qo.getPageSize());
        }
        List<?> result = stockIncomeBillMapper.queryForList(qo);
        return new PageResult(rows, result, qo.getCurrentPage(), qo.getPageSize());
    }

    public void audit(Long id) {
        //1.先通过id查询当前订单
        StockIncomeBill stockIncomeBill = stockIncomeBillMapper.selectByPrimaryKey(id);
        //2.判断当前订单处于未审核状态
        if (stockIncomeBill != null && StockIncomeBill.STATUS_NORMAL == stockIncomeBill.getStatus()) {
            //3.更新审核相关信息
            stockIncomeBill.setAuditor(UserContext.getcurrentUser());
            stockIncomeBill.setAuditTime(new Date());
            stockIncomeBill.setStatus(StockIncomeBill.STATUS_AUDITED);
            //4.更新订单
            stockIncomeBillMapper.audit(stockIncomeBill);

            //===========库存操作============
            productStockService.stockIncome(stockIncomeBill);
        }
    }
}
